import { CodeEnum } from "./enum/CodeEnum";

type httpCallback = (data: any) => void;

class Http {

    public request(path: string, data: any, decodeFunc: any, callback: httpCallback)
    {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 4000;

        xhr.onreadystatechange = function()
        {
            if(xhr.readyState == 4)
            { // 接收完毕
                if(xhr.status >= 200 && xhr.status < 400)
                {
                    let buffer = new Uint8Array(xhr.response);
                    let response = decodeFunc(buffer);
                    callback(response);
                }
                else
                {
                    callback({code: CodeEnum.timeout});
                }
            }
        }.bind(this);

        xhr.open("POST", "http://127.0.0.1:9020" + path, true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.responseType = "arraybuffer";
        xhr.send(data);
    }

    public checkResponseData(data: any, showErrorCode: boolean = true) : boolean
    {
        if (data.code != CodeEnum.success)
        {
            if (showErrorCode) {
                cc.error(`response error code is ${data.code}`);
            }
            return false;
        }
        return true;
    }

}

export let httpManager = new Http();
